<template>
  <div class="m-tabs-card">
    <div class="m-tabs-header">
      <!--这里遍历子组件的props属性-->
      <div v-for="(item,index) in tabs" 
      @click="tabClick($event, index)"
      :class="activeName_ == item.props.name ? 'm-tab-title m-tab-title-seleted':'m-tab-title'" 
      :key="item.props.name">
        {{item.props.title}}
      </div>
    </div>
    <div class="m-tabs-body">
      <!--这里定义插槽-->
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Tabs',
  props: {
    activeName: { // 定义默认活跃的面板名称
      type: [String,Number],
      default: undefined
    }
  },
  data() {
    return {
      activeName_: this.activeName,
      tabs: []
    }
  },
  created() {
    // 通过this.$slots.default()可以拿到子组件
    // console.log(this.$slots.default())
    if(this.$slots.default) {
      // 获取插槽中名为TabPane的子组件
      this.tabs = this.$slots.default().filter(item => item.type.name === 'TabPane')
    }
  },
  methods: {
    tabClick(e, index) {
      // 设置当前活跃的面板名称
      this.activeName_ = this.tabs[index].props.name
      // 导出属性中的name和title值
      let {name, title} = this.tabs[index].props
      // 这里定义事件，父组件可以通过配置@on-tab-change进行监听
      this.$emit('on-tab-change',{
        index: index,
        name: name,
        title: title
      })
    }
  }
}
</script>

<style scoped>
.m-tabs-header{
  height: 40px;
  border: 1px solid #cccccc;
  display: flex;
  background: #eeeeee;
}
.m-tab-title{
  padding-left: 18px;
  padding-right: 18px;
  display: flex;
  align-items: center;
  color: #333333;
  font-size: 14px;
  border-right: 1px solid #cccccc;
  cursor: pointer;
}
.m-tab-title-seleted{
  color: #ffffff;
  background: #3778bc;
}
.m-tabs-body{
  border: 1px solid #cccccc;
  border-top: none;
}
</style>